<template>
  <h1>员工列表练习</h1>
<el-form style="width: 500px; margin: 0 auto;">
  <el-form-item label="姓名">
    <el-input v-model="user.name" placeholder="请输入姓名" ></el-input>
  </el-form-item>
  <el-form-item label="工资">
    <el-input v-model="user.salary" placeholder="请输入工资" ></el-input>
  </el-form-item>
  <el-form-item label="岗位">
    <el-input v-model="user.job" placeholder="请输入岗位" ></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="addUser">点我提交</el-button>
  </el-form-item>
</el-form>
  <hr>
  <el-table :data="users" style="width: 500px; margin:0 auto;">
    <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
    <el-table-column label="姓名" prop="name"></el-table-column>
    <el-table-column label="工资" prop="salary"></el-table-column>
    <el-table-column label="岗位" prop="job"></el-table-column>
    <el-table-column label="操作" align=" center">
      <template #default="scope">
        <el-button type="danger" @click="del(scope.row,scope.$index)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import { ref } from 'vue'
import {ElMessage} from "element-plus";

//定义对象用来保存用户输入的数据
const user = ref({name:'', salary:'', job:''});
//定义数组用来保存表格数据
const users = ref ([]);
//定义添加员工的方法
const addUser = () => {
  //验证员工信息
  if (user.value.name.trim() == '' || user.value.salary.trim() == '' || user.value.job.trim() == '') {
    ElMessage.error('请填写完整员工信息!');
    return;
  }
  users.value.push(user.value); //将收集到的员工数据存入数组中
  user.value={name:'', salary:'', job:''} //清空输入框的值，否则会对一个值反复修改！
  console.log(users.value);
}

//定义删除员工的方法
const del = (emp,index) => { //emp为当前员工对象，index为当前员工在数组中的索引
  if (confirm('确定要删除'+emp.name+'吗？')){
  user.value.splice(index, 1); //删除当前员工
  ElMessage.success('删除成功！');}
}

</script>

<style scoped>

</style>